package com.dmap.admin.service.backgroundv2.impl;

import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.DeviceParam;
import com.dmap.admin.controller.backgroundv2.param.DeviceSelectParam;
import com.dmap.admin.dao.DeviceMapper;
import com.dmap.admin.po.Company;
import com.dmap.admin.po.Device;
import com.dmap.admin.po.DeviceExample;
import com.dmap.admin.po.Project;
import com.dmap.admin.service.backgroundv2.CompanyService;
import com.dmap.admin.service.backgroundv2.DeviceService;
import com.dmap.admin.service.backgroundv2.ProjectService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 25/05/18
 * \* Description:设备相关接口实现类
 * \
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private ProjectService projectService;
    @Resource
    private CompanyService companyService;

    @Override
    public Device insertDevice(DeviceParam param) {
        Device device = new Device();
        if (StringUtils.isNotBlank(param.getTypeId()) && StringUtils.isNumeric(param.getTypeId())) {
            device.setTypeId(Long.valueOf(param.getTypeId()));
        }
        device.setFirmware(param.getFirmware());
        device.setDeviceName(param.getDeviceName());
        device.setDeviceImageUrl(param.getDeviceImageUrl());
        device.setStatus(param.getStatus());
        device.setNote(param.getNote());
        device.setCreateTime(System.currentTimeMillis() / 1000);
        device.setUpdateTime(device.getCreateTime());
        int success = deviceMapper.insertSelective(device);
        return (success == 1) ? device : null;
    }

    @Override
    public boolean updateDevice(DeviceParam param) {
        Device device = new Device();
        device.setId(Long.valueOf(param.getId()));
        device.setFirmware(param.getFirmware());
        device.setDeviceName(param.getDeviceName());
        device.setDeviceImageUrl(param.getDeviceImageUrl());
        device.setStatus(param.getStatus());
        device.setNote(param.getNote());
        device.setUpdateTime(System.currentTimeMillis() / 1000);
        return deviceMapper.updateByPrimaryKeySelective(device) == 1;
    }

    @Override
    public boolean validateFirmwareOrNameIsExist(String firmware, String deviceName) {
        boolean returnValue = true;
        DeviceExample example = new DeviceExample();
        //匹配 固件编号 进行查询
        DeviceExample.Criteria criteria1 = example.createCriteria();
        //匹配 设备名称 进行查询
        DeviceExample.Criteria criteria2 = example.createCriteria();
        if (StringUtils.isNotBlank(firmware)) {
            criteria1.andFirmwareEqualTo(firmware);
        }
        if (StringUtils.isNotBlank(deviceName)) {
            criteria2.andDeviceNameEqualTo(deviceName);
        }
        example.or(criteria2);
        List<Device> list = deviceMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            returnValue = false;
        }
        return returnValue;
    }

    @Override
    public Device selectById(Long id) {
        return deviceMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Device> selectByCompanyId(Long companyId) {
        Company company = companyService.selectById(companyId);
        DeviceExample example = new DeviceExample();
        //如果是总公司则直接返回所有设备列表
        if (company.getCompanyType() != AdminConstant.COMPANY_TYPE_HEAD) {
            List<Project> projectList = projectService.selectByCompanyId(companyId);
            if (CollectionUtils.isEmpty(projectList)) {
                return Collections.emptyList();
            }
            List<Long> deviceIdList = new ArrayList<>();
            for (Project project : projectList) {
                if (project != null && project.getDeviceId() != null && !project.getDeviceId().equals(0L)) {
                    deviceIdList.add(project.getDeviceId());
                }
            }
            if (CollectionUtils.isEmpty(deviceIdList)) {
                return Collections.emptyList();
            }
            example.createCriteria().andIdIn(deviceIdList);
        }
        int pageSize = deviceMapper.countByExample(example);
        if (pageSize < 1) {
            return Collections.emptyList();
        }
        example.setLimitStart(0);
        example.setLimitEnd(pageSize);
        return deviceMapper.selectByExample(example);
    }

    @Override
    public List<Device> selectByDeviceSelectParam(DeviceSelectParam param) {
        DeviceExample example = this.getDeviceSelectParamExample(param.getTypeId(), param.getSearchKeyword());
        //根据前端所传参数不同生成对应的orderBy子句
        String orderByClause = AdminConstant.getOrderByClauseMap().getOrDefault(param.getSortField(), AdminConstant.UPDATE_TIME)
                + AdminConstant.getOrderByClauseSequenceMap().getOrDefault(param.getOrder(), AdminConstant.DESC);
        example.setOrderByClause(orderByClause);
        example.setLimitStart((param.getPageIndex() - 1) * param.getPageSize());
        example.setLimitEnd(param.getPageSize());
        return deviceMapper.selectByExample(example);
    }

    @Override
    public int countByDeviceSelectParam(DeviceSelectParam param) {
        DeviceExample example = this.getDeviceSelectParamExample(param.getTypeId(), param.getSearchKeyword());
        return deviceMapper.countByExample(example);
    }

    private DeviceExample getDeviceSelectParamExample(String typeId, String searchKeyword) {
        DeviceExample example = new DeviceExample();
        //根据 固件编号 模糊搜索
        DeviceExample.Criteria criteria1 = example.createCriteria();
        //根据 设备名称 模糊搜索
        DeviceExample.Criteria criteria2 = example.createCriteria();
        //如果 typeId 不为空，则匹配设备类型ID进行查询
        if (StringUtils.isNotBlank(typeId) && StringUtils.isNumeric(typeId)
                && !Long.valueOf(typeId).equals(0L)) {
            criteria1.andTypeIdEqualTo(Long.valueOf(typeId));
            criteria2.andTypeIdEqualTo(Long.valueOf(typeId));
        }
        if (StringUtils.isNotBlank(searchKeyword)) {
            criteria1.andFirmwareLike("%" + searchKeyword + "%");
            criteria2.andDeviceNameLike("%" + searchKeyword + "%");
        }
        example.or(criteria2);
        return example;
    }

    @Override
    public int countByDeviceTypeId(Long deviceTypeId) {
        DeviceExample example = new DeviceExample();
        example.createCriteria().andTypeIdEqualTo(deviceTypeId);
        return deviceMapper.countByExample(example);
    }

}